import * as drag from './drag.js'

function get_array_max(data)
{
    if(typeof data == 'number')
        return data
    if(data instanceof Array){
        let max = 0
        for(var i = 0; i < data.length; ++i){
            let cur = get_array_max(data[i])
            if(cur > max)
                max = cur
        }
        return max
    } else{
        return 0
    }
}

function get_array_median(data){
    var compare = function(a, b){return a-b}
    data.sort(compare)
    var length = data.length
    if(length % 2 == 0){
        return (data[length / 2] + data[length/2 - 1])/2
    } else {
        return data[(length-1) / 2]
    }
}

function timestamp_to_date(Timestamp) {
    let date1 = new Date(Timestamp);
    return date1.toLocaleDateString().replace('/\//g', "-") + " " + date1.toTimeString().substr(0, 8);
}

function formate_data_tap_latency(data)
{
//    console.log(data)
    var res = {};
    res['col_names'] = ["timestamp", "environment", "FPS",
        "latency_up", "p2kUp", "k2cUp",
        "latency_down", "p2kDown", 'k2cDown'];

    res['timestamp'] = new Array();
    res['environment'] = new Array();
    res['FPS'] = new Array();

    res['latency_up'] = new Array();
    res['latency_point_up'] = new Array();
    res['p2kUp'] = new Array();
    res['k2cUp'] = new Array();

    res['latency_down'] = new Array();
    res['latency_point_down'] = new Array();
    res['p2kDown'] = new Array();
    res['k2cDown'] = new Array();

    res['latency'] = new Array();

    for(var i = 0; i < data.length; ++i){
        res['timestamp'].push(data[i]["timestamp"]);
        res['environment'].push(data[i]["version"]);
        res['FPS'].push(data[i]["FPS"]);

        res['latency_up'].push(data[i]["latency_up"]);
        res['p2kUp'].push(data[i]["p2kUp"]);
        res['k2cUp'].push(data[i]["k2cUp"]);
        res['latency_down'].push(data[i]["latency_down"]);
        res['p2kDown'].push(data[i]["p2kDown"])
        res['k2cDown'].push(data[i]["k2cDown"])

        var latency_point_up = [];
        for(var j = 0; j < data[i]["p2kUp"].length; ++j){
            latency_point_up.push(data[i]["p2kUp"][j] + data[i]["k2cUp"][j])
        }
        res['latency_point_up'].push(latency_point_up);

//        console.log("latency_point_up: " + get_array_median(latency_point_up))

        var latency_point_down = [];
        for(var j = 0; j < data[i]["p2kDown"].length; ++j){
            latency_point_down.push(data[i]["p2kDown"][j] + data[i]["k2cDown"][j])
        }
        res['latency_point_down'].push(latency_point_down);

        res['latency'].push((get_array_median(latency_point_up)+get_array_median(latency_point_down)) / 2)
    }
//    console.log(res['latency'])
    return res;
}

function formate_data_screen_latency(data)
{
//    console.log(data)
    var res = {};
    res['col_names'] = ["timestamp", "environment", "FPS",
        "latency_w2b", "latency_b2w"];

    res['timestamp'] = new Array();
    res['environment'] = new Array();
    res['FPS'] = new Array();

    res['latency_w2b'] = new Array();
    res['latency_b2w'] = new Array();

    res['latency'] = new Array();

    for(var i = 0; i < data.length; ++i){
        res['timestamp'].push(data[i]["timestamp"]);
        res['environment'].push(data[i]["version"]);
        res['FPS'].push(data[i]["FPS"]);

        res['latency_b2w'].push(data[i]["deltas_b2w"]);
        res['latency_w2b'].push(data[i]["deltas_w2b"]);

        res['latency'].push((get_array_median(data[i]["deltas_b2w"])+get_array_median(data[i]["deltas_w2b"])) / 2)

    }
    return res;
}


function formate_data_drag_latency(data)
{
    var res = {};
    res['col_names'] = ["timestamp", "environment", "FPS",
        "latency"];

    res['timestamp'] = new Array();
    res['environment'] = new Array();
    res['FPS'] = new Array();

    res['latency'] = new Array();

    for(var i = 0; i < data.length; ++i){
        res['timestamp'].push(data[i]["timestamp"]);
        res['environment'].push(data[i]["version"]);
        res['FPS'].push(data[i]["FPS"]);
//        res['latency'].push(data[i]["latency"]);
        res['latency'].push(
            drag.calculateDragLatency(data[i].finger_time, data[i].finger_pos, data[i].laser_time, data[i].laser_pos)
        );
    }
    return res;
}


function formate_data_audio_latency_playback(data)
{
//    console.log(data)
    var res = {};
    res['col_names'] = ["timestamp", "environment", "FPS",
        'FrameRate', "FramesPerBuffer",
        "latency", "J2N", "P2Q", "Q2W"];

    res['timestamp'] = new Array();
    res['environment'] = new Array();
    res['FPS'] = new Array();

    res['FrameRate'] = new Array();
    res['FramesPerBuffer'] = new Array();

    res['latency'] = new Array();
    res['J2N'] = new Array();
    res['P2Q'] = new Array();
    res['Q2W'] = new Array();

    for(var i = 0; i < data.length; ++i){
        res['timestamp'].push(data[i]["timestamp"]);
        res['environment'].push(data[i]["version"]);
        res['FPS'].push(data[i]["FPS"]);

        res['FrameRate'].push(data[i]["FrameRate"]);
        res['FramesPerBuffer'].push(data[i]["FramesPerBuffer"]);

        var latency = [];
        for(var j = 0; j < data[i]["deltas_Queue2Wire"].length; ++j){
            latency.push(data[i]["deltas_J2N"][j] + data[i]["deltas_Play2Queue"][j] + data[i]["deltas_Queue2Wire"][j])
        }
        res['latency'].push(latency);
        res['J2N'].push(data[i]["deltas_J2N"]);
        res['P2Q'].push(data[i]["deltas_Play2Queue"]);
        res['Q2W'].push(data[i]["deltas_Queue2Wire"]);

        console.log(i + ": " +
            get_array_median(data[i]["deltas_J2N"]) + ", " +
            get_array_median(data[i]["deltas_Play2Queue"]) + ", " +
            get_array_median(data[i]["deltas_Queue2Wire"]));
    }
    return res;
}


function formate_data_audio_latency_record(data)
{
//    console.log(data)
    var res = {};
    res['col_names'] = ["timestamp", "environment", "FPS",
        'latency'];

    res['timestamp'] = new Array();
    res['environment'] = new Array();
    res['FPS'] = new Array();

    res['latency'] = new Array();

    for(var i = 0; i < data.length; ++i){
        res['timestamp'].push(data[i]["timestamp"]);
        res['environment'].push(data[i]["version"]);
        res['FPS'].push(data[i]["FPS"]);

        res['latency'].push(data[i]["deltas_mic"]);
    }
    return res;
}

function get_option_default(chart_data, type_name)
{
    var option = {
        title: {
//            text: type_name + " 箱线图",
            left: 'center',
        },
        tooltip: {
            trigger: 'item',
            axisPointer: {
                type: 'shadow'
            }
        },
        xAxis: {
            type: 'category',
//            data: chart_data[0].axisData,
            boundaryGap: true,
            nameGap: 30,
            splitArea: {
                show: true
            },
            axisLabel: {
                formatter: '{value}'
            },
            splitLine: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            name: '延迟时间(毫秒 ms)',
            min: 0,
//            max: max_value,
            splitArea: {
              show: false
            }
        },
        grid: {
            left: '10%',
            top: '20%',
            right: '10%',
            bottom: '15%'
        },
        dataZoom: [
            {
              type: 'inside',
              start: 0,
              end: 100
            },
            {
              show: true,
              type: 'slider',
              top: '90%',
              xAxisIndex: [0],
              start: 0,
              end: 100
            }
        ],

        legend:{
            y: '10%',
            data:[]
        },
    }
    return option;
}

function get_option_tap_latency(data, type_name)
{
//    console.log(data)

    var chart_data = [];
    chart_data.push(echarts.dataTool.prepareBoxplotData(data['latency_point_up']));
    chart_data.push(echarts.dataTool.prepareBoxplotData(data['latency_point_down']));
//    console.log(chart_data)
    let max_value = Math.max(get_array_max(data['latency_point_up']), get_array_max(data['latency_point_down']));
    max_value = (parseInt((max_value / 10).toFixed(0)) + 1) * 10;

    var option = get_option_default();
    option.title.text = type_name + " 箱线图"
    option.xAxis.data = chart_data[0].axisData
    option.yAxis.max = max_value
    option.legend = {
        y: '10%',
        data: ['点击抬起 Up', '点击落下 Down']
    }

    option.series = [
        {
            name: '点击抬起 Up',
            type: 'boxplot',
            data: chart_data[0].boxData,
            tooltip: {formatter: formatter}
        },
        {
            name: '点击落下 Down',
            type: 'boxplot',
            data: chart_data[1].boxData,
            tooltip: {formatter: formatter}
        }
    ];

    function formatter(param) {
        var index = parseInt(param.name);
        var data_tag = 'latency_point_' + ['up', 'down'][param.seriesIndex];

        return [
            '测试时间：' + timestamp_to_date(data['timestamp'][index]),
            '测试环境：' + data['environment'][index],
            'FPS：' + data['FPS'][index],
            '数据量：' + data[data_tag][index].length,
            'upper: ' + param.data[5].toFixed(1),
            'Q1: ' + param.data[4].toFixed(1),
            'Med: ' + param.data[3].toFixed(1),
            'Q3: ' + param.data[2].toFixed(1),
            'lower: ' + param.data[1].toFixed(1)
        ].join('<br/>')
    }
    return option;
}


function get_option_screen_latency(data, type_name)
{
    var chart_data = [];
    chart_data.push(echarts.dataTool.prepareBoxplotData(data['latency_w2b']));
    chart_data.push(echarts.dataTool.prepareBoxplotData(data['latency_b2w']));

    let max_value = Math.max(get_array_max(data['latency_w2b']), get_array_max(data['latency_b2w']));
    max_value = (parseInt((max_value / 10).toFixed(0)) + 1) * 10;

    var option = get_option_default();
    option.title.text = type_name + " 箱线图"
    option.xAxis.data = chart_data[0].axisData
    option.yAxis.max = max_value
    option.legend = {
        y: '10%',
        data: ['屏幕变黑色', '屏幕变白色']
    }

    option.series = [
        {
            name: '屏幕变黑色',
            type: 'boxplot',
            data: chart_data[0].boxData,
            tooltip: {formatter: formatter}
        },
        {
            name: '屏幕变白色',
            type: 'boxplot',
            data: chart_data[1].boxData,
            tooltip: {formatter: formatter}
        }
    ];

    function formatter(param) {
//        console.log(param)

        var index = parseInt(param.name);
        var data_tag = 'latency_' + ['w2b', 'b2w'][param.seriesIndex];
//        console.log(data_tag)

        return [
            '测试时间：' + timestamp_to_date(data['timestamp'][index]),
            '测试环境：' + data['environment'][index],
            'FPS：' + data['FPS'][index],
            '数据量：' + data[data_tag][index].length,
            'upper: ' + param.data[5].toFixed(1),
            'Q1: ' + param.data[4].toFixed(1),
            'Med: ' + param.data[3].toFixed(1),
            'Q3: ' + param.data[2].toFixed(1),
            'lower: ' + param.data[1].toFixed(1)
        ].join('<br/>')
    }
    return option;
}


function get_option_drag_latency(data, type_name)
{
    var chart_data = data['latency'];

    let max_value = get_array_max(data['latency']);
    max_value = (parseInt((max_value / 10).toFixed(0)) + 1) * 10;
    var axisData = []
    for(var i = 0; i < data.length; ++i){
        axisData.push(timestamp_to_date(data["timestamp"][i]))
    }
    var option = get_option_default();
    option.title.text = '拖动延迟' + " 条形图"
//    option.xAxis.data = axisData
    option.yAxis.max = max_value

    option.series = [
        {
            name: 'latency',
            type: 'bar',
            data: chart_data,
            tooltip: {formatter: formatter}
        }
    ];

//
//    console.log(chart_data)
//    console.log(axisData)

    function formatter(param) {
        var index = param.dataIndex;
        return [
            '测试时间：' + timestamp_to_date(data['timestamp'][index]),
            '测试环境：' + data['environment'][index],
            'FPS：' + data['FPS'][index],
            'Value：' + param.data.toFixed(1),
        ].join('<br/>')
    }
    return option;
}

function get_option_audio_latency_playback(data, type_name)
{
    var chart_data = [];
    chart_data.push(echarts.dataTool.prepareBoxplotData(data['latency']));

    let max_value = get_array_max(data['latency']);
    max_value = (parseInt((max_value / 10).toFixed(0)) + 1) * 10;

    var option = get_option_default();
    option.title.text = "声音播放延迟" + " 箱线图"
    option.xAxis.data = chart_data[0].axisData
    option.yAxis.max = max_value

    option.series = [
        {
            name: '延迟数据',
            type: 'boxplot',
            data: chart_data[0].boxData,
            tooltip: {formatter: formatter}
        }
    ];

    function formatter(param) {
        var index = parseInt(param.name);
        return [
            '测试时间：' + timestamp_to_date(data['timestamp'][index]),
            '测试环境：' + data['environment'][index],
            'FPS：' + data['FPS'][index],
            'FrameRate：' + data['FrameRate'][index],
            'FramesPerBuffer：' + data['FramesPerBuffer'][index],
            '数据量：' + data['latency'][index].length,
            '<br/>Max: ' + param.data[5].toFixed(1),
            'Q1: ' + param.data[4].toFixed(1),
            'Med: ' + param.data[3].toFixed(1),
            'Q3: ' + param.data[2].toFixed(1),
            'Min: ' + param.data[1].toFixed(1)
        ].join('<br/>')
    }
    return option;
}


function get_option_audio_latency_record(data, type_name)
{
    var chart_data = [];
    chart_data.push(echarts.dataTool.prepareBoxplotData(data['latency']));

    let max_value = get_array_max(data['latency']);
    max_value = (parseInt((max_value / 10).toFixed(0)) + 1) * 10;

    var option = get_option_default();
    option.title.text = "录音延迟" + " 箱线图"
    option.xAxis.data = chart_data[0].axisData
    option.yAxis.max = max_value

    option.series = [
        {
            name: '延迟数据',
            type: 'boxplot',
            data: chart_data[0].boxData,
            tooltip: {formatter: formatter}
        }
    ];

    function formatter(param) {
        var index = parseInt(param.name);
        return [
            '测试时间：' + timestamp_to_date(data['timestamp'][index]),
            '测试环境：' + data['environment'][index],
            'FPS：' + data['FPS'][index],
            '数据量：' + data['latency'][index].length,

            '<br/>Max: ' + param.data[5].toFixed(1),
            'Q1: ' + param.data[4].toFixed(1),
            'Med: ' + param.data[3].toFixed(1),
            'Q3: ' + param.data[2].toFixed(1),
            'Min: ' + param.data[1].toFixed(1)
        ].join('<br/>')
    }
    return option;
}

function get_option(data, type)
{
    var res = {};
    if(type == "tap_latency"){
        res = get_option_tap_latency(data, type)
    } else if(type == "screen_latency"){
        res = get_option_screen_latency(data, type)
    } else if(type == "drag_latency"){
        res = get_option_drag_latency(data, type)
    } else if(type == "audio_latency_record"){
        res = get_option_audio_latency_record(data, type)
    } else if(type == "audio_latency_playback"){
        res = get_option_audio_latency_playback(data, type)
    }

//    console.log(res)

    return res;
}

function formate_data(data, type)
{
    var res = {};
    if(type == "tap_latency"){
        res = formate_data_tap_latency(data)
    } else if(type == "screen_latency"){
        res = formate_data_screen_latency(data)
    } else if(type == "drag_latency"){
        res = formate_data_drag_latency(data)
    } else if(type == "audio_latency_record"){
        res = formate_data_audio_latency_record(data)
    } else if(type == "audio_latency_playback"){
        res = formate_data_audio_latency_playback(data)
    }

//    console.log(res)
    var android=0, ue = 0;
    var android_count=0, ue_count = 0;

    console.log(res['environment'])
    console.log(res['latency'])

    for(var i = 0; i < res['environment'].length; ++i){
        if(res['latency'][i] instanceof Array){
            var value = get_array_median(res['latency'][i]);
        } else{
            var value = res['latency'][i];
        }
        if(res['environment'][i] == 'android'){
            android_count+= 1;
            android += value;
        } else{
            ue_count += 1;
            ue += value;
        }
    }

    console.log("android: " + android / android_count + " \tue: " + ue / ue_count)

    return res;
}

export { formate_data, get_option};
//export default chart_data;